package com.chat.websocket.controller;

/**
 * SunJingxuan
 * 2022 \ 08 \ 10
 */

import com.chat.websocket.entity.dto.MessageContentDTO;
import com.chat.websocket.entity.dto.SendMessageDTO;
import com.chat.websocket.entity.enums.GlobalConstants;
import com.chat.websocket.entity.http.Response;
import com.chat.websocket.entity.vo.MessageContentVO;
import com.chat.websocket.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping(value = "/message")
@Slf4j
public class MessageController {

	@Resource
	private MessageService messageService;

	/**
	 * 给好友发消息
	 * @reqstMethod POST
	 * @param sendMessageDTO com.chat.websocket.entity.dto.SendMessageDTO
	 * @return com.chat.websocket.entity.http.Response<Boolean>
	 */
	@PostMapping("/sendMessageToUser")
	public ResponseEntity<Response<Boolean>> sendMessageToUser(@RequestBody SendMessageDTO sendMessageDTO) {
		try {
			log.info("给单独用户发消息");
			Boolean sendMessage = messageService.sendMessageToUser(sendMessageDTO);
			return ResponseEntity.ok(Response.success(sendMessage));
		} catch (IOException e) {
			log.error("发送失败", e);
			return ResponseEntity.ok(Response.error(GlobalConstants.SEND_MESSAGE_ERR.getCode(), GlobalConstants.SEND_MESSAGE_ERR.getMessage()));
		} catch (Exception e) {
			log.error("服务错误", e);
			return ResponseEntity.ok(Response.error());
		}
	}

	/**
	 * 历史消息查询
	 * @reqstMethod POST
	 * @param messageContentDTO com.chat.websocket.entity.dto.MessageContentDTO
	 * @return com.chat.websocket.entity.http.Response<Boolean>
	 */
	@PostMapping("/getHistoryMessage")
	public ResponseEntity<Response<List<MessageContentVO>>> getHistoryMessage(@RequestBody MessageContentDTO messageContentDTO) {
		try {
			log.info("查询历史消息");
			List<MessageContentVO> historyMessageList = messageService.getHistoryMessage(messageContentDTO);
			return ResponseEntity.ok(Response.success(historyMessageList));
		} catch (Exception e) {
			log.error("服务错误", e);
			return ResponseEntity.ok(Response.error());
		}
	}

	/**
	 * 已读消息
	 * @reqstMethod GET
	 * @param messageId 消息id long
	 * @return com.chat.websocket.entity.http.Response<String>
	 */
	@GetMapping("/haveReadMessage/{messageId}")
	public ResponseEntity<Response<String>> haveReadMessage(@PathVariable Long messageId) {
		try {
			log.info("已读消息");
			messageService.haveReadMessage(messageId);
			return ResponseEntity.ok(Response.success(null));
		} catch (Exception e) {
			log.error("服务错误", e);
			return ResponseEntity.ok(Response.error());
		}
	}
}
